package com.bancomer.batch.validators.impl;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.FileReader;

import com.bancomer.batch.Constants;
import com.bancomer.batch.MapConstants;
import com.bancomer.batch.pojo.Alert;
import com.bancomer.batch.pojo.FileHelper;
import com.bancomer.batch.pojo.ValidationResult;
import com.bancomer.batch.util.FilesWriter;
import com.bancomer.batch.util.NumberComparator;
import com.bancomer.batch.validators.GeneralValidator;


public class SensitiveCollectiveValidator implements GeneralValidator{
	private String type = null;
	private String profile = null;
	private String consecutive = null;
	private StringBuffer condition = new StringBuffer();

	public ValidationResult doSC(FileHelper inputFile,Alert alert){
		Map<String,String> filterSC = new HashMap<String,String>();
		FileHelper parameterFile = null;
		ValidationResult result = new ValidationResult();
		FileReader input = null;
		BufferedReader buffer = null;
		String positions;
		String names;
		String[] columnsPositions;
		String[] columnsNames;
		String line;
		String load="";
		Map<String,int[]> columnPositions = new HashMap<String, int[]>();
		try{
			MapConstants properties = MapConstants.getInstance(alert.getProperties().getProperty("constantsFile"));
			final Properties alertConstants = properties.getConstants();
			for(FileHelper file : alert.getOutputFiles()){
				if(file.getName().equals("pigScriptParameters.properties")){
					parameterFile = file;
					break;
				}
			}
			input = new FileReader(parameterFile.getLocalPath()+parameterFile.getName());
			buffer = new BufferedReader(input);
			line=buffer.readLine();
			while(line!=null){
				if(line.contains(inputFile.getProperties().getProperty("layoutName"))){
					load = line.split("=")[1];
					break;
				}
				line = buffer.readLine();
			}
			buffer.close();
			load = load.replace("com.bancomer.pig.functions.IndexOfLoader", "");
			load = load.replaceAll("[\\(\\'\\ \\)]","");
			positions = load.split("as")[0];
			names = load.split("as")[1];
			columnsPositions = positions.split(",");
			columnsNames = names.split(",");
	
			for(int i=0;i<columnsPositions.length;i++){
				int[] indexPositions = new int[2];
				indexPositions[0]=Integer.valueOf(columnsPositions[i].split("-")[0]);
				indexPositions[1]=Integer.valueOf(columnsPositions[i].split("-")[1]);
				columnPositions.put(columnsNames[i].split(":")[0],indexPositions);
			}
		
		
			input = new FileReader(inputFile.getLocalPath()+inputFile.getName());
			buffer = new BufferedReader(input);	
			line = buffer.readLine();
			while (line != null)   {
				result = doConditionSC(line,columnPositions,alertConstants);
				if(result.getSucces()==false){
					buffer.close();
					return result;
				}
				line = buffer.readLine();
	    	}
			if("".equals(condition.toString().trim())){
				result.setMessage("No hay par�metros de colectivos sensibles para la alerta "+alert.getName()+ " en el archivo "+inputFile.getName());
				result.setSucces(false);
				buffer.close();
				return result;
			}
			condition.append(")");
			filterSC.put("scFilter", condition.toString());
			FilesWriter.writePropertiesFile(parameterFile,filterSC);
		}
		catch(Exception e){
			result.setMessage(e.getMessage());
			result.setSucces(false);
		}
		return result;
		
	}
	
	public ValidationResult doConditionSC(String line,Map<String,int[]> columnPositions, Properties alertConstants){
		ValidationResult result = new ValidationResult();
		int[] indexPositions;
		indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL1"));
		String scIndicator = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
		indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL2"));
		String alert06 = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
		String profileType = "";
		String attribute = "";
		String concept = "";
		String operator = "";
		String scValue = "";
		String scProfile = "";
		String consecutiveName = "";
		String dateCondition = "";
		if(alertConstants.getProperty("PCS").equals(scIndicator)&&alertConstants.getProperty("ALERT_06").equals(alert06)){
			indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL6"));
			attribute = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
			if(alertConstants.getProperty("ATTRIBUTE").equals(attribute)){
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL3"));
				profileType = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL5"));
				concept = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL7"));
				operator = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL10"));
				scValue = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
				indexPositions = columnPositions.get(alertConstants.getProperty("TAB_CS_COL11"));
				scProfile = line.substring(indexPositions[0],NumberComparator.compareLength(indexPositions[1],line.length())).trim();
				if("".equals(operator)||"=".equals(operator)){
					operator="==";
				}			
				if(alertConstants.getProperty("CSR01").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR01;
					consecutiveName="$1";
				}
				else if(alertConstants.getProperty("CSR02").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR02;
					consecutiveName="$2";
				}
				else if(alertConstants.getProperty("CSR03").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR03;
					consecutiveName="$3";
				}
				else if(alertConstants.getProperty("CSR04").equals(concept)){
					//dateCondition="DaysBetween("+alertConstants.getProperty("DEFINITION_CSR04+"Dt, (datetime)ToDate('"+scValue+"', 'yyyy-MM-dd'))"+operator+"(long)0";
					dateCondition="DaysBetween($4, (datetime)ToDate('"+scValue+"', 'yyyy-MM-dd'))"+operator+"(long)0";
				}
				else if(alertConstants.getProperty("CSR05").equals(concept)){
					//dateCondition="DaysBetween("+alertConstants.getProperty("DEFINITION_CSR05+"Dt, (datetime)ToDate('"+scValue+"', 'yyyy-MM-dd'))"+operator+"(long)0";
					dateCondition="DaysBetween($5, (datetime)ToDate('"+scValue+"', 'yyyy-MM-dd'))"+operator+"(long)0";
				}
				else if(alertConstants.getProperty("CSR06").equals(concept)){
					//dateCondition="DaysBetween("+alertConstants.getProperty("DEFINITION_CSR06+"Dt, (datetime)ToDate('"+scValue+"', 'yyyy-MM-dd'))"+operator+"(long)0";
					dateCondition="DaysBetween($6, (datetime)ToDate('"+scValue+"', 'yyyy-MM-dd'))"+operator+"(long)0";
				}
				else if(alertConstants.getProperty("CSR07").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR07;
					consecutiveName="$11";
				}
				else if(alertConstants.getProperty("CSR08").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR08;
					consecutiveName="$12";
				}
				else if(alertConstants.getProperty("CSR09").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR09;
					consecutiveName="$13";
				}
				else if(alertConstants.getProperty("CSR10").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR10;
					consecutiveName="$14";
				}
				else if(alertConstants.getProperty("CSR11").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR11;
					consecutiveName="$15";
				}
				else if(alertConstants.getProperty("CSR12").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR12;
					consecutiveName="$17";
				}
				else if(alertConstants.getProperty("CSR13").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR13;
					consecutiveName="$18";
				}
				else if(alertConstants.getProperty("CSR14").equals(concept)){
					//consecutiveName=alertConstants.getProperty("DEFINITION_CSR14;
					consecutiveName="$19";
				}
				else if(alertConstants.getProperty("CSR15").equals(concept)){							
					Calendar fechaActual = Calendar.getInstance();
					String dia = Integer.toString(fechaActual.get(Calendar.DAY_OF_MONTH));
					dia = (dia.length()<2)?"0"+dia:dia;
					String mes = Integer.toString(fechaActual.get(Calendar.MONTH)+1);
					mes = (mes.length()<2)?"0"+mes:mes;
					String anio = Integer.toString(fechaActual.get(Calendar.YEAR)-Integer.valueOf(scValue));
					String anio_1 = Integer.toString(fechaActual.get(Calendar.YEAR)-Integer.valueOf(scValue)-1);
					String fechaCS = anio+"-"+mes+"-"+dia;
					String fechaCS_1 = anio_1+"-"+mes+"-"+dia;
					if(operator.equals(">=")){
						//dateCondition="DaysBetween("+alertConstants.getProperty("DEFINITION_CSR04+"Dt, (datetime)ToDate('"+fechaCS+"', 'yyyy-MM-dd'))<=(long)0";
						dateCondition="DaysBetween($4, (datetime)ToDate('"+fechaCS+"', 'yyyy-MM-dd'))<=(long)0";
					}
					else if(operator.equals("<=")){
						//dateCondition="DaysBetween("+alertConstants.getProperty("DEFINITION_CSR04+"Dt, (datetime)ToDate('"+fechaCS_1+"', 'yyyy-MM-dd'))>(long)0";
						dateCondition="DaysBetween($4, (datetime)ToDate('"+fechaCS_1+"', 'yyyy-MM-dd'))>(long)0";
					}
					else if(operator.equals("==")){
						//dateCondition="(DaysBetween("+alertConstants.getProperty("DEFINITION_CSR04+"Dt, (datetime)ToDate('"+fechaCS_1+"', 'yyyy-MM-dd'))>(long)0 AND DaysBetween("+alertConstants.getProperty("DEFINITION_CSR04+"Dt, (datetime)ToDate('"+fechaCS+"', 'yyyy-MM-dd'))<=(long)0)";
						dateCondition="(DaysBetween($4, (datetime)ToDate('"+fechaCS_1+"', 'yyyy-MM-dd'))>(long)0 AND DaysBetween($4, (datetime)ToDate('"+fechaCS+"', 'yyyy-MM-dd'))<=(long)0)";
					}
					else if(operator.equals("<")){
						//dateCondition="DaysBetween("+alertConstants.getProperty("DEFINITION_CSR04+"Dt, (datetime)ToDate('"+fechaCS+"', 'yyyy-MM-dd'))>(long)0";
						dateCondition="DaysBetween($4, (datetime)ToDate('"+fechaCS+"', 'yyyy-MM-dd'))>(long)0";
					}
					else if(operator.equals(">")){
						//dateCondition="DaysBetween("+alertConstants.getProperty("DEFINITION_CSR04+"Dt, (datetime)ToDate('"+fechaCS_1+"', 'yyyy-MM-dd'))<=(long)0";
						dateCondition="DaysBetween($4, (datetime)ToDate('"+fechaCS_1+"', 'yyyy-MM-dd'))<=(long)0";
					}
				}
				else{
					result.setMessage("No se encontr� el consecutivo ("+concept+")");
					result.setSucces(false);
					return result;
				}
				if(type==null&&profile==null&&consecutive==null){
					type = profileType;
					profile = scProfile;
					consecutive = concept;
					condition.append("((");
					if(!dateCondition.equals("")){
						condition.append(dateCondition+")");
					}
					else{
						condition.append(consecutiveName+" "+operator+" '"+scValue+"')");
					}
				}
				else if ((!"".equals(type)&&type.equals(profileType))&&(!"".equals(profile)&&profile.equals(scProfile))){
					if(consecutive.equals(concept)){
						condition.deleteCharAt(condition.length()-1);							
						if(!dateCondition.equals("")){
							condition.append(" OR "+dateCondition+")");
						}
						else{
							condition.append(" OR "+consecutiveName+" "+operator+" '"+scValue+"')");
						}
					}
					else if(!consecutive.equals(concept)){
						consecutive=concept;
						if(!dateCondition.equals("")){
							condition.append(" AND ("+dateCondition+")");
						}
						else{
							condition.append(" AND ("+consecutiveName+" "+operator+" '"+scValue+"')");
						}
					}
				}
				else if ((!"".equals(type)&&!type.equals(profileType))&&(!"".equals(profile)&&!profile.equals(scProfile))){
					type=profileType;
					profile=scProfile;
					consecutive=concept;
					condition.append(")");
					if(!dateCondition.equals("")){
						condition.append(" OR (("+dateCondition+")");
					}
					else{
						condition.append(" OR (("+consecutiveName+" "+operator+" '"+scValue+"')");
					}
				}
				else{
					result.setMessage("No es posible generar los par�metros. Tipo ("+type+") o perfil ("+profile+") incorrectos");
					result.setSucces(false);
					return result;
				}
			}
		}
		return result;
	}
	
	@Override
	public ValidationResult executeValidation(FileHelper fileHelper,
			Object... obj) {
		// TODO Auto-generated method stub
		ValidationResult result = new ValidationResult();
		try {
			result = doSC(fileHelper,(Alert)obj[0]);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result.setMessage("Class: SensitiveCollectiveValidator - "+e.getMessage());
			result.setSucces(false);
		}
		return result;
	}
}

